package com.kitty.game.task.service.taskHandler;

import com.kitty.game.role.model.Role;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.ActivityService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.task.TaskDataPool;
import com.kitty.game.task.message.RespTasksDel;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.mina.message.MessagePusher;
import com.kitty.game.role.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**师门任务处理类*/
@Service
public class SchoolTaskHandler extends TaskHandler {
    Logger logger = LoggerFactory.getLogger(getClass());
    /**自动寻路的最小等级*/
    private static final short MIN_LEVEL_AUTO_WALK = 30;

    @Override
    public String getTaskButtons(Role role, NPC npc) {
        logger.info("师门任务验证逻辑");

        /**满足以下条件时，需要显示领取师门任务按钮
         *
         * 1、师门任务功能已经开启
         * 2、当前没有接取师门任务
         * 3、主线任务已经完成领取师门任务
         * 4、NPC为领取师门任务NPC
         * */

        RoleService roleService = SpringUtils.getRoleService();
        /**没有开启功能时，返回*/
//        if (!roleService.isOpenFunction(role, FunctionType.SCHOOL_TASK)) {return "";}

        /**已经有接取师门任务时，返回*/
        if (isAcceptedSchoolTask(role)) {return "";}

        /**主线任务还没到领取师门任务时，返回*/
        if (!role.getTask().isFinished(TaskDataPool.MAIN_SCHOOL_TASKID)) {return "";}

        /**当前npc不是对应NPC时，返回*/
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.SCHOOL_GUIDE_TASKID, role);
        String npcName = taskSet.getNpcName();
        if (!npcName.equals(npc.getName())) {return "";}

        return taskSet.getButtton();
    }

    @Override
    public TaskType getTaskType() {
        return TaskType.SCHOOL;
    }

    /**显示师门任务的那个引导任务，点击后会走到师尊那领取师门任务*/
    public void pushGuideTask(Role role) {
        RoleService roleService = SpringUtils.getRoleService();
        /**没有开启功能时，返回*/
//        if (!roleService.isOpenFunction(role, FunctionType.SCHOOL_TASK)) {return ;}

        /**已经有接取师门任务时，返回*/
        if (isAcceptedSchoolTask(role)) {return ;}

        /**主线任务还没到领取师门任务时，返回*/
        if (!role.getTask().isFinished(TaskDataPool.MAIN_SCHOOL_TASKID)) {return ;}

        /**活动次数已经用完时，返回*/
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        int remainCount = activityService.getRemainCount(role, ActivityType.SCHOOL_TASK);
        if (remainCount <= 0) {return ;}

        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.SCHOOL_GUIDE_TASKID, role);
        pushTask(role, taskSet);
    }

    /**是否已经接取师门任务*/
    public boolean isAcceptedSchoolTask(Role role) {
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        List<TaskSet> taskList = taskService.getAcceptedTaskListMatchTaskType(role, TaskType.SCHOOL);
        /**获得的已接取师门任务列表没有时，则返回false*/
        if (taskList == null || taskList.isEmpty()) {return false;}

        return true;
    }

    /**接取师门任务*/
    public void acceptTask(Role role) {
        this.logger.info("领取师门任务");
        /**判断当前是否可以接取，可以时  随机接取师门任务*/
        if (!canAcceptTask(role)) {
            return ;
        }

        /**可以接取任务时，随机接取一个师门任务*/
        TaskSet randTaskSet = getRandomSchoolTask(role);
        if (randTaskSet == null) {return ;}

        acceptTask(role, randTaskSet);
    }

    /**判断是否可以接取师门任务*/
    private boolean canAcceptTask(Role role) {
        /**当前次数已经用完，则不能接取了*/
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        boolean isHave = activityService.isHaveRemainCount(role, ActivityType.SCHOOL_TASK);
        if (!isHave) {
            /**没有活动次数了，返回false*/
            return false;
        }

        /**已经有接取的师门任务，返回false*/
        if (isAcceptedSchoolTask(role)) {
            return false;
        }

        /**放弃任务后的等待时间没到时，返回false*/
        if (isWaitGiveUpCD(role)) {
            return false;
        }

        return true;
    }

    private TaskSet getRandomSchoolTask(Role role) {
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        List<Integer> schoolTaskList = taskService.getTaskListByType(TaskType.SCHOOL);
        if (schoolTaskList.isEmpty()) {
            /**没有可接的任务时，返回*/
            // TODO 需要记录下日志？？
            return null;
        }

        int randIndex = ThreadLocalRandom.current().nextInt(schoolTaskList.size());
        int taskId = schoolTaskList.get(randIndex);

        return taskService.getTaskSet(taskId, role);
    }

    /**获得当不能换取师门任务时，给NPC的显示内容*/
    public String getNpcContentNotAccept(Role role) {
        ActivityService activityService = SpringUtils.getBean(ActivityService.class);
        boolean isHave = activityService.isHaveRemainCount(role, ActivityType.SCHOOL_TASK);
        if (!isHave) {
            return "你今日为师门做了很多事，辛苦你了，前去休息吧。[离开/离开]";
        }

        if (isWaitGiveUpCD(role)) {
            return "你刚才已经放弃师门任务，还是休息一阵再来吧。[离开/离开]";
        }

        return null;
    }

    /**是否是放弃任务后的等待时间还没到*/
    private boolean isWaitGiveUpCD(Role role) {
        long giveUpTime = role.getTask().getGiveUpTime(TaskType.SCHOOL);
        if (giveUpTime > 0 && (System.currentTimeMillis()-giveUpTime) < TaskDataPool.DELAY_TIME_AFTER_GIVEUP_SCHOOL) {
            return true;
        }

        return false;
    }

    @Override
    public void doBeforeAccept(Role role, TaskSet taskSet) {
        super.pushEndTask(role, taskService.getTaskSet(TaskDataPool.SCHOOL_GUIDE_TASKID, role));
    }

    @Override
    public void doAfterAccept(Role role, TaskSet taskSet) {
        super.doAfterAccept(role, taskSet);

        /**接取任务时清除之前放弃任务的时间记录*/
        role.getTask().removeGiveUpTime(TaskType.SCHOOL);

        /**师门任务大于30级后才自动寻路*/
        if (role.getLevel() >= MIN_LEVEL_AUTO_WALK) {
            RespAutoWalk respAutoWalk = new RespAutoWalk();
            respAutoWalk.setTaskName(taskSet.getTaskName());
            String dest = taskSet.getTaskZhiyin();
            respAutoWalk.setDest(dest);
            MessagePusher.pushMessage(role, respAutoWalk);
        }
    }

    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        TaskInfo taskInfo = super.getTaskInfo(role, taskSet);
        if (taskService.isMatchTaskType(taskSet, TaskType.SCHOOL)) {
            ActivityService activityService = SpringUtils.getBean(ActivityService.class);
            int doStep = activityService.getFinishCount(role, ActivityType.SCHOOL_TASK) + 1;
            int remainCount = activityService.getRemainCount(role, ActivityType.SCHOOL_TASK);
            taskInfo.setShow_name(taskInfo.getShow_name() + "(" + doStep + "/" + ActivityType.SCHOOL_TASK.getTotalCount() + ")");
            taskInfo.setTaskInfo(MessageFormat.format(taskInfo.getTaskInfo(), doStep, remainCount-1));
            taskInfo.setTaskName("sm-010");
        }
        return taskInfo;
    }

    @Override
    public void doAfterSubmit(Role role, TaskSet taskSet) {
        addActivityCount(role, taskSet);

        super.doAfterSubmit(role, taskSet);

        /**师门任务在接取了下一任务之后把当前任务重置掉，如果不重置的话玩家可以直接接取任务组中的最后一个任务*/
        role.getTask().resetTask(taskSet.getId());
    }

    /**增加任务活动次数*/
    private void addActivityCount(Role role, TaskSet taskSet) {
        /** 当前任务是否有下一任务，没有下一任务，表示当前是这组任务最后一个。需要加活动次数*/
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet nextTask = taskService.getNextTask(taskSet, role);
        if (nextTask == null) {
            ActivityService activityService = SpringUtils.getBean(ActivityService.class);
            activityService.addFinishCount(role, ActivityType.SCHOOL_TASK, 1);
            logger.trace("师门剩余任务数量：" + activityService.getFinishCount(role, ActivityType.SCHOOL_TASK));
        }
    }

    @Override
    public TaskSet getNextTask(Role role, TaskSet taskSet) {
        /**通过任务中的下一任务id查找是否有后续任务*/
        TaskSet nextTask = taskService.getNextTask(taskSet, role);
        if (nextTask != null) {
            return nextTask;
        }

        /**判断当前是否可以接取任务，如果可以接取，则随机下一任务*/
        if (canAcceptTask(role)) {
            return getRandomSchoolTask(role);
        }

        return null;
    }

    @Override
    public void giveReward(Role role, TaskSet taskSet) {
        super.giveReward(role, taskSet);

    }

    /**放弃师门任务*/
    public void giveUpTask(Role role) {
        TaskSet doingSchoolTask = getDoingSchoolTask(role);
        if (doingSchoolTask == null) {
            /**找不到师门任务时，返回*/
            return ;
        }

        /**放弃*/
        giveUpTask(role, doingSchoolTask);
    }

    private TaskSet getDoingSchoolTask(Role role) {
        List<TaskSet> taskList = taskService.getAcceptedTaskListMatchTaskType(role, TaskType.SCHOOL);
        /**理论上在做的师门只会有一个*/
        return taskList.get(0);
    }

    @Override
    public void pushEndTask(Role role, TaskSet taskSet) {
        RespTasksDel respTasksDel = new RespTasksDel();
        respTasksDel.setList(new ArrayList<>());
        respTasksDel.getList().add("sm-010");
        MessagePusher.pushMessage(role, respTasksDel);
    }

    @Override
    public boolean canGiveUpTask(Role role, TaskSet taskSet) {
        return true;
    }

    @Override
    public void doAfterGiveUp(Role role, TaskSet taskSet) {
        role.getTask().addGiveUpTime(TaskType.SCHOOL, System.currentTimeMillis());

        super.doAfterGiveUp(role, taskSet);

        /**放弃任务时，显示引导任务*/
        pushGuideTask(role);
    }

    @Override
    public boolean canResetTask(Role role, TaskSet taskSet) {
        return true;
    }

    @Override
    public void doAfterReset(Role role, TaskSet taskSet) {
        super.doAfterReset(role, taskSet);

        /**删除任务时，显示引导任务*/
        pushGuideTask(role);
    }

    /**接取师门任务*/
    public void acceptSchoolTask(Role role, NPC npc) {
        String content = getNpcContentNotAccept(role);
        if (content != null) {
            /**返回提示信息*/
            SpringUtils.getNpcService().sendNpcContent(role, npc, content);

            return ;
        }

        acceptTask(role);
    }
}
